<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Admin\Model;

use Admin\Logic\NestedSets;
use Think\Page;

class GoodsModel extends \Think\Model
{

    /**
     * 开启批量验证
     * @var bool
     */
    protected $patchValidate = true;

    /**
     * 批量验证规则
     * 1. 商品名必填
     * 2. 商品分类必填
     * 3. 品牌必填
     * 4. 供货商必填
     * 5. 市场价必填,必须是货币
     * 6. 商城价格必填,必须是货币
     * 7. 库存必填,必须是数字
     * ...
     */
    protected $_validate = [
        ['name', 'require', '商品名称不能为空'],
        ['sn', '', '货号已存在', self::VALUE_VALIDATE],
        ['goods_category_id', 'require', '商品分类不能为空'],
        ['brand_id', 'require', '品牌不能为空'],
        ['supplier_id', 'require', '供货商不能为空'],
        ['market_price', 'require', '市场价不能为空'],
        ['market_price', 'currency', '市场价不合法'],
        ['shop_price', 'require', '售价不能为空'],
        ['shop_price', 'currency', '售价不合法'],
        ['stock', 'require', '库存不能为空'],
    ];

    /**
     * 开启自动完成
     * @var array
     */
    protected $_auto = [
        ['sn', 'goodsNum', self::MODEL_INSERT, 'callback'],
        ['goods_status', 'goodsStatus', self::MODEL_BOTH, 'callback'],
        ['inputtime', NOW_TIME, self::MODEL_INSERT],
    ];

    /**
     * 计算商品状态
     * @return int|number
     */
    public function goodsStatus()
    {
        $status = I('post.goods_status');
        if (isset($status)) {
            return array_sum(I('post.goods_status'));
        } else {
            return 0;
        }
    }

    /**
     * 添加商品信息
     * @return bool
     */
    public function addGoods()
    {
        unset($this->data['id']);
        /*var_dump($this->data);
        exit;*/
        $this->startTrans();
        // 1.添加商品
        if (($goods_id = $this->add()) === false) {
            $this->rollback();
            return false;
        }
        $content = [];
        $content['goods_id'] = $goods_id;
        $content['content'] = I('post.content');
        // 2.添加商品详情
        if (M('GoodsIntro')->add($content) === false) {
            $this->rollback();
            return false;
        }
        //3.添加相册
        $gallery_model = M('GoodsGallery');
        $galleries = [];
        foreach (I('post.path') as $path) {
            $galleries[] = [
                'goods_id' => $goods_id,
                'path' => $path
            ];
        }
        //($galleries);exit;
        $result = $gallery_model->addAll($galleries);
        //如果上传了相册,并且相册保存失败,就回滚
        if ($galleries && $result === false) {
            $this->rollback();
            return false;
        }

        $this->commit();
        return true;
    }

    /**
     * 获取商品的品牌、供货商、所属分类信息
     * @return array
     */
    public function getGoodsInfo()
    {
        //$goods_sn = $this->goodsNum();

        // 1.>>获取分类
        $categories = M('GoodsCategory')->select();
        // 2.>>获取所有品牌
        $brands = M('Brand')->select();
        // 3.获取所有供应商
        $suppliers = M('Supplier')->where('status>0')->select();
        // 4.获取商品相册

        return compact('categories', 'brands', 'suppliers');

    }

    /**
     * 获取商品编号
     * @param string $sn
     * @return integer|string
     */
    public function goodsNum($sn)
    {
        $this->startTrans();
        // 格式SN2016062900001
        if ($sn) {
            return $sn;
        }

        $date = date('Ymd');
        $goodsNum_model = M('GoodsNum');

        if ($num = $goodsNum_model->getFieldByDate($date, 'goods_num')) {
            ++$num;
            $data = ['date' => $date, 'goods_num' => $num];
            $flag = $goodsNum_model->save($data);
        } else {
            $num = 1;
            $data = ['date' => $date, 'goods_num' => $num];
            $flag = $goodsNum_model->add($data);
        }

        if ($flag === false) {
            $this->rollback();
        }

        $sn = str_pad($num, 5, '0', STR_PAD_LEFT);
        $sn = 'SN' . $date . $sn;
        return $sn;

    }

    /**
     * 获取所有商品的列表和分页信息
     * @param array $cond
     * @return array
     */
    public function getList(array $cond = [])
    {
        $cond = array_merge(['status' => 1], $cond);
        $count = $this->where($cond)->count();
        $page_setting = C('PAGE_SETTING');
        $page = new Page($count, $page_setting['PAGE_SIZE']);
        $page->setConfig('theme', $page_setting['PAGE_THEME']);
        $page_html = $page->show();
        $rows = $this->where($cond)->page(I('get.p', 1), $page_setting['PAGE_SIZE'])->select();

        foreach ($rows as $key => $value) {
            /*if ($value['goods_status'] & 1) {
                $value['is_best'] = true;
            } else {
                $value['is_best'] = false;
            }*/
            $value['is_best'] = $value['goods_status'] & 1 ? true : false;
            $value['is_new'] = $value['goods_status'] & 2 ? true : false;
            $value['is_hot'] = $value['goods_status'] & 4 ? true : false;
            $rows[$key] = $value;
        }

        return compact('rows', 'page_html');
    }

    /**
     * 获取单个商品的详细信息
     * @param integer $id
     * @return mixed
     */
    public function findGoods($id)
    {
        $row = $this->find($id);
        $goods_status = $row['goods_status'];
        $status = [];

        if ($goods_status & 1) {
            $status[] = 1;
        }

        if ($goods_status & 2) {
            $status[] = 2;
        }

        if ($goods_status & 4) {
            $status[] = 4;
        }

        $row['goods_status'] = json_encode($status);
        $row['content'] = M('GoodsIntro')->getFieldByGoodsId($id, 'content');
        // 获取相册
        $row['galleries'] = M('GoodsGallery')->getFieldByGoodsId($id, 'id,path');
        return $row;
    }

    /**
     * 更新商品操作
     * 同时更新三张表
     * @return bool
     */
    public function saveGoods()
    {
        $request_data = $this->data;
        $this->startTrans();
        //1.保存基本信息
        if ($this->save() === false) {
            $this->rollback();
            return false;
        }
        //2.保存详细描述
        $data = [
            'goods_id' => $request_data['id'],
            'content' => I('post.content', '', false),
        ];
        $goods_intro_model = M('GoodsIntro');
        if ($goods_intro_model->save($data) === false) {
            $this->rollback();
            return false;
        }
        //3.保存相册
        $gallery = M('GoodsGallery');
        //echo $request_data['id'];exit;
        $del_result = $gallery->where("goods_id={$request_data['id']}")->delete();

        if ($del_result === false) {
            echo 3;
            exit;
            $this->rollback();
            return false;
        }
        $paths = I('post.path');
        $galleries = [];

        foreach ($paths as $path) {
            $galleries[] = [
                'goods_id' => $request_data['id'],
                'path' => $path
            ];
        }
        $result = $gallery->addAll($galleries);

        if ($result === false) {
            $this->rollback();
            return false;
        }
        $this->commit();
        return true;
    }
}
